package servlet;

import entity.Data;
import exception.DataAccessException;
import util.JdbcUtil;
import util.JsonUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/query")
public class QueryServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("QueryServlet.service()");

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out=response.getWriter();

        String key=request.getParameter("key");

        System.out.println("key = " + key);

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        List<Data> dataList=new ArrayList<>();
        try {
            con= JdbcUtil.getConnection();

            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_data ")
                    .append("where message like ? ")
                    .append("or keywords like ? ")
                    .toString();

            ps=con.prepareStatement(sql);
            ps.setString(1,key+"%");
            ps.setString(2,key+"%");

            rs=ps.executeQuery();

            while (rs.next()){
                Data data=new Data();
                data.setId(rs.getInt("id"));
                data.setMessage(rs.getString("message"));
                dataList.add(data);
            }

            con.commit();

        } catch (Exception e){
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            throw new DataAccessException("数据访问失败",e);
        } finally {
            JdbcUtil.close(con,ps,rs);
        }

        System.out.println("dataList = " + dataList);

        out.print(JsonUtil.toJson(dataList));
    }
}
